#ifndef _HEAD_H
#define _HEAD_H
#include <my_head.h>
#endif

#ifndef _QUEUEMANAGER_H
#define _QUEUEMANAGER_H
#include "headfile/allqueue/queueManager.h"
#endif

//#ifndef _USER_H
//#define _USER_H
//#include"./headfile/alluser/user.h"
//#endif

void initQueueManager(queueManager * qmanager)
{
    printf("queueManager.c /18:正在初始化任务队列\n");
    qmanager->taskListHead = NULL;
    qmanager->taskListTail = NULL;
    qmanager->currSizeTask = 0;
}

//因为在这用recv接受,必须用int标记到底接收了多少
static int createTask(int connect_fd , qNode * qn)
{
    
    memset(&(qn->usermes) , 0 ,sizeof(qn->usermes));
    memset(&(qn->usermes.content) , 0 , sizeof(qn->usermes.content));
    memset(&(qn->usermes.user) , 0 , sizeof(qn->usermes.user));
    
    printf("queueManager.c/ 31: sizeof(qn->usermes.user) = %ld\n" ,  sizeof(qn->usermes.user));

    qn->connect_fd = connect_fd;
    qn->funcPara = NULL;
    qn->func = NULL;
    qn->next = NULL;
    


    //先读头，再根据头读不读后面的
    int ret = recv(connect_fd , &(qn->usermes) , sizeof(qn->usermes) - MAX_BUF_FILE , 0);
    printf("queueManager.c /42:ret is %d , s-max is %ld , user name is %s \n" , ret , sizeof(qn->usermes) - MAX_BUF_FILE , qn->usermes.user.name);

    //小心段错误
    if(ret <= 0 || ret < (int)sizeof(qn->usermes) - MAX_BUF_FILE)
    {   
        close(connect_fd);
        return -1;
    }

    if(qn->usermes.contentSize != 0)ret+=recv(connect_fd , qn->usermes.content , qn->usermes.contentSize , 0);
    printf("queueManager.c /52:此次读到%d , 数据中标记的大小是%d\n" , ret , qn->usermes.contentSize);
    return ret;
}
void inserQue(queueManager * qmanager , int connect_fd)
{
    qNode * qn = (qNode *)malloc(sizeof(qNode));
    CHECK_ERROR(qn , NULL , "queueManager.c/ 40:任务节点创建失败\n");

    int flag = createTask(connect_fd , qn); //返回大于0是总共接收了多少,==-1是失败
    if(flag == -1)
    {
        free(qn);//若创建任务失败则回收qn,避免内存泄漏
        return ;//如果返回-1表明客户端断开链接，直接返回
    }
    if(qmanager->currSizeTask == 0)
    {
        qmanager->taskListHead = qn;
        qmanager->taskListTail = qn;
    }
    else
    {
        qmanager->taskListTail->next = qn;
        qmanager->taskListTail = qn;
    }
    qmanager->currSizeTask++;
    printf("queueManager.c /55:任务入队\n");
    return ;
}

//移动任务节点，return 值拷贝, 因为任务出队后要free
qNode delQue(queueManager * qmanager)
{
    qNode ret = *(qmanager->taskListHead);
    qNode * tmpDel = qmanager->taskListHead;
    
    if(qmanager->currSizeTask == 1)
    {
        qmanager->taskListHead = NULL;
        qmanager->taskListTail = NULL;
    }
    else
    {
        qmanager->taskListHead = qmanager->taskListHead->next;
    }
    free(tmpDel);
    qmanager->currSizeTask--;
    printf("queueManager.c /56:任务出队\n");
    return ret;
}

//不删除任务节点
qNode getTask(queueManager * qmanager)
{
    return *(qmanager->taskListHead);
}
